package com.knowledge.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.common.cache.GlobalLocalCache;
import com.knowledge.common.constant.GlobalConstant;
import com.knowledge.dao.entity.SysUser;
import com.knowledge.dao.entity.TokenEntity;
import com.knowledge.dao.mapper.SysUserMapper;
import com.knowledge.service.SysUserService;
import com.knowledge.service.TokenService;
import com.knowledge.utils.JwtUtil;
import com.knowledge.common.enums.ErrorCode;
import com.knowledge.utils.UserThreadLocal;
import com.knowledge.vo.LoginUserVo;
import com.knowledge.vo.Result;
import com.knowledge.vo.UserVo;
import com.knowledge.vo.params.ChangePwdParam;
import com.knowledge.vo.params.SetAdminParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zzz
 * @create 2022-02-10 17:32
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    @Override
    public SysUser findUserById(Long id) {
        SysUser sysUser = sysUserMapper.selectById(id);
        if(sysUser==null){
            sysUser = new SysUser();
            sysUser.setNickname("Dr.Ding");
        }
        return sysUser;
    }

    @Override
    public SysUser findUser(String account, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount,account);
        queryWrapper.eq(SysUser::getPassword,password);
        queryWrapper.select(SysUser::getAccount,SysUser::getAdmin, SysUser::getId,SysUser::getAvatar,SysUser::getNickname);
        queryWrapper.last("limit 1");
        return sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public Result findUserByToken(String token) {
        /**
         * 1.token合法性校验 是否为空, 解析是否车工 redis是否存在
         * 2.如果校验失败 返回错误
         * 3.如果成功 返回对应的结果 LoginUserVo
         */

        SysUser sysUser = checkToken(token);
        if(sysUser==null){
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(String.valueOf(sysUser.getId()));
        loginUserVo.setAccount(sysUser.getAccount());
        loginUserVo.setNickname(sysUser.getNickname());
        loginUserVo.setAvatar(sysUser.getAvatar());
        loginUserVo.setAdmin(sysUser.getAdmin());
        return Result.success(loginUserVo);
    }


    @Override
    public SysUser findUserByAccount(String account) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount,account);
        queryWrapper.last("limit 1");
        return sysUserMapper.selectOne(queryWrapper);
    }

    @Override
    public SysUser checkToken(String token) {
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, Object> stringObjectMap = JwtUtil.checkToken(token);
        if(stringObjectMap==null){
            return null;
        }

        SysUser sysUser = GlobalLocalCache.getLoginUser(token);
        if(sysUser == null){
            return null;
        }
        return sysUser;
    }

    @Override
    public UserVo findUserVoById(Long authorId) {
        SysUser sysUser = sysUserMapper.selectById(authorId);
        if(sysUser==null){
            sysUser = new SysUser();
            sysUser.setId(1L);
            sysUser.setAvatar("/static/user/admin.png");
            sysUser.setNickname("玩家国度");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(sysUser,userVo);
        return userVo;
    }

    @Override
    public void initEffectiveUser() {
        List<TokenEntity> tokenEntities = tokenService.listEffectiveToken();
        if (tokenEntities != null && tokenEntities.size() > 0){
            List<Long> userIds = tokenEntities.stream().map(TokenEntity::getUserId).collect(Collectors.toList());
            Map<Long, String> tokenMap = tokenEntities.stream()
                    .collect(Collectors.toMap(TokenEntity::getUserId, TokenEntity::getTokenId, (v1,v2)->v2));
            List<SysUser> list = listByIds(userIds);
            for (SysUser sysUser : list){
                GlobalLocalCache.cache(tokenMap.get(sysUser.getId()), sysUser);
            }
        }
    }

    @Override
    public Result changePassword(ChangePwdParam changePwdParam) {

        //校验原密码
        Long userId = UserThreadLocal.get().getId();
        if (!checkPwd(changePwdParam.getOldPwd(), userId)) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_ERRROR.getCode(), ErrorCode.ACCOUNT_PWD_ERRROR.getMsg());
        }

        if (!changePwdParam.getNewPwd().equals(changePwdParam.getTwiceNewPwd())) {
            return Result.fail(ErrorCode.CHECK_PWD_ERRROR.getCode(), ErrorCode.CHECK_PWD_ERRROR.getMsg());
        }

        //更新密码
        updateUserPwd(changePwdParam.getNewPwd(), userId);

        return Result.success();
    }

    private void updateUserPwd(String newPwd, Long userId) {
        String newPassword = DigestUtils.md5Hex(newPwd + GlobalConstant.SALT);
        SysUser user = new SysUser();
        user.setId(userId);
        user.setPassword(newPassword);
        sysUserMapper.updateById(user);
    }

    private boolean checkPwd(String oldPwd, Long userId) {
        String password = DigestUtils.md5Hex(oldPwd + GlobalConstant.SALT);
        LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getId, userId)
                .eq(SysUser::getPassword, password);
        return sysUserMapper.selectCount(query) > 0;
    }

    @Override
    public Result setAdmin(SetAdminParam param) {
        SysUser user = new SysUser();
        user.setAdmin(param.getAdmin());
        user.setId(param.getUserId());
        sysUserMapper.updateById(user);
        return Result.success();
    }
}
